package br.com.localfloripa.services;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

import br.com.localfloripa.entities.Endereco;
import br.com.localfloripa.util.StringUtils;

import com.google.code.geocoder.Geocoder;
import com.google.code.geocoder.GeocoderRequestBuilder;
import com.google.code.geocoder.model.GeocodeResponse;
import com.google.code.geocoder.model.GeocoderRequest;
import com.google.code.geocoder.model.GeocoderResult;

@Service("geoCodingService")
public class GeoCodingService {
	
	private Geocoder geoCoder;

	public GeoCodingService() {
		this.geoCoder = new Geocoder();
	}
	
	public Map<String,BigDecimal> geocode(Endereco endereco) {
		
		Map<String, BigDecimal> localizacao = new HashMap<String, BigDecimal>();
		
		String pais = "Brasil";
		String uf = endereco.getMunicipio().getEstado().getSigla();
		String municipio = endereco.getMunicipio().getNome();
		String bairro = endereco.getBairro();
		String rua = endereco.getRua();
		Integer numero = endereco.getNumero();
		String cep = endereco.getCep();
		String address = StringUtils.replaceSpecial(rua +","+numero+" - "+bairro+","+municipio+","+uf+","+cep+","+pais);
		GeocoderRequest request = new GeocoderRequestBuilder().setAddress(address).setLanguage("pt-br").getGeocoderRequest();
		GeocodeResponse response = geoCoder.geocode(request);
		
		if (response != null) {
			List<GeocoderResult> geoCoderResult = response.getResults();
			for (GeocoderResult result : geoCoderResult) {
				localizacao.put("long", result.getGeometry().getLocation().getLng());
				localizacao.put("lat", result.getGeometry().getLocation().getLat());						
			}
		}		
		
		return localizacao;
	}
	
	

}
